<?php
function migrateRoutes()
{
    $db = db::$db;

    $sql = "DROP TABLE IF EXISTS routes";
    $db->exec($sql);

    $sql = "CREATE TABLE IF NOT EXISTS routes (
        id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
        user_id INT(6) UNSIGNED NOT NULL,
        title VARCHAR(250),
        rating FLOAT DEFAULT -1,
        route TEXT NOT NULL,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        route_type INT(6) UNSIGNED NOT NULL DEFAULT 2
    )";

    $db->exec($sql);
}


function _addRoute() {
    $route = json_encode( Req::$data['route'] );
    $userId = (int) verifyToken(Req::$data['token']??0);

    $routeType = (int) (Req::$data['route_type'] ?? 2);
    $db = db::$db;
    $stmt = $db->prepare("INSERT INTO routes (user_id, route, route_type) VALUES (?, ?, ?)");
    $stmt->execute([$userId, $route, $routeType]);
    $id = $db->lastInsertId();

    return $db->lastInsertId()?['id'=>$db->lastInsertId()]:null;
//    return $stmt->execute([$userId, $route]);
}

function _getRouteById()
{
    $routeId = (int) Req::$data['id'];
    $db = db::$db;
    $userId = (int) verifyToken(Req::$data['token']??0);
    $stmt = $db->prepare("SELECT * FROM routes WHERE id = ? AND user_id = ?");
    $stmt->execute([$routeId, $userId]);
    $data = $stmt->fetch(PDO::FETCH_ASSOC);
    return $data;
}

function getUserRoutes()
{
//    $route = Req::$data['route'];
//    $userId = (int) verifyToken(Req::$data['token']??0);
//    $success = addRoute($userId, $route);
//    echo json_encode(['success' => $success]);
//    $userId = (int) verifyToken(Req::$data['token']??0);
//    $stmt = $db->prepare("SELECT * FROM routes WHERE user_id = ?");
//    $stmt->execute([$userId]);
//    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}


function getAllRoutes()
{
    $db = db::db();
    $userId = (int) verifyToken(Req::$data['token']??0);
    $stmt = $db->prepare("SELECT * FROM routes WHERE user_id = ?");
    $stmt->execute([$userId]);
    return $stmt->fetchAll(PDO::FETCH_ASSOC);
}
